<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/6/11
 * Time: 下午1:26
 */
namespace Modules\Admin\Auth;

use Illuminate\Support\Facades\Cache;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Hash;
use App\Sms;

class AdminAuth
{
    /**
     * 已经登录的用户信息
     *
     * @var AdminUser
     */
    public $userData;

    protected $sessionKey = '__ADMIN_LOGIN__';

    /**
     * @param $username
     * @param $password
     * @param $sms_code
     *
     * @return bool
     */
    public function attempt($username, $password,$sms_code)
    {
        $admin = AdminUser::where('username', $username)->first();
        if (!$admin) {
            return false;
        }
        if (!password_verify($password, $admin->password)) {
            return false;
        }
        if ($admin->mobile && !Sms::validation($admin->mobile, $sms_code)) {
            return false;
        }
        $this->login($admin);
        return true;
    }

    public function findByUserName($username)
    {
        $admin = AdminUser::where('username', $username)->first();
        if($admin){
            return $admin->toArray();
        }
        return null;
    }

    /**
     * 验证是否登录
     *
     * @return bool
     */
    public function check()
    {
        $isLogin = session($this->sessionKey);
        return $isLogin ? true: false;
    }

    /**
     * 登录用户信息
     *
     * @param AdminUser $user
     */
    public function login(AdminUser $user)
    {
        $this->userData = $user;
        session([
           $this->sessionKey => $user->id
        ]);
    }

    /**
     * 登出
     */
    public function logout()
    {
        app('session')->forget($this->sessionKey);
        $this->userData = null;
    }

    /**
     * 获取登录的用户信息
     *
     * @param $key
     * @return mixed
     */
    public function user($key = null)
    {
        if (!$this->userData) {
            $id = session($this->sessionKey);

            $this->userData = Cache::remember('admin_user_id_' . $id, 10, function() use ($id) {
                AdminUser::with('role')->find($id);
            });
            if (!$this->userData) {
                $this->userData = AdminUser::with('role')->find($id);
            }
        }
        if (!$this->userData) {
            $this->logout();
        }
        if ($key) {
            return $this->userData->$key;
        } else {
            return $this->userData;
        }
    }

    /**
     * 修改密码
     *
     * @author River
     *
     * @param $old
     * @param $new
     *
     * @return bool
     */
    public function changePassword($old, $new)
    {
        $user = $this->user();
        if (!password_verify($old, $user->password)) {
            return false;
        }
        $user->password = Hash::make($new);
        $user->save();
        return true;
    }
}